/*
 * LandmarksFrame.java
 *
 * Copyright 2008 David D. Emory
 * 
 * This file is part of Five Points. See <http://www.fpdev.org> for
 * additional information regarding the project.
 * 
 * Five Points is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Five Points is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Five Points.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.fpdev.apps.admin.gui;

import org.fpdev.util.gui.GUIFactory;
import java.awt.*;
import java.awt.event.*;
import java.util.Iterator;
import java.util.List;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.table.*;
import org.fpdev.core.basenet.Landmarks;
import org.fpdev.apps.admin.ACEvent;
import org.fpdev.apps.admin.AdminClient;
import org.fpdev.apps.admin.EventTypes;
import org.fpdev.apps.admin.gui.dialogs.LandmarkEditLocationDialog;

public class LandmarksFrame extends JFrame implements ActionListener {

  private AdminClient av_;

  //private CNode selNode_;
  private int selRow_,  minSelRow_,  maxSelRow_;
  //private CLandmark selLM_;
  private List<Landmarks.LandmarkInfo> lmiList_;
  private String selName_,  selLoc_;
  private JTable table_;
  private JScrollPane tScrollPane_;
  private ListSelectionModel mainLSM_; //, groupLSM_;
  private int mode_;
  private JLabel selLabel_,  locLabel_;//, groupLabel_;
  private JComboBox newCBox_;
  private JButton updateBtn_,  revertBtn_;
  private JButton editNameBtn_,  editAltNamesBtn_,  editLocBtn_;
  private JButton zoomBtn_,  delBtn_,  newBtn_;
  private JTextField nameText_,  altNamesText_,  locText_;
  private JPopupMenu popup_;
  private JMenuItem addressMI_,  nodeMI_,  groupMI_,  aliasMI_;
  public static final int MODE_DEFAULT = 1;
  public static final int MODE_EDITING_GROUP = 2;
  public static final int MODE_CREATING_NODE = 3;
  public static final int MODE_EDITING_NODE = 4;
  public static final int MODE_CREATING_ALIAS = 5;
  public static final int MODE_EDITING_ALIAS = 6;

  public LandmarksFrame(AdminClient cv) {
    super("Edit Landmarks");

    av_ = cv;
    selRow_ = minSelRow_ = maxSelRow_ = -1;
    mainLSM_ = null;
    mode_ = MODE_DEFAULT;

    // table 
    table_ = new JTable();
    table_.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    ListSelectionModel rowLSM = table_.getSelectionModel();
    rowLSM.addListSelectionListener(new ListSelectionListener() {

      public void valueChanged(ListSelectionEvent e) {
        if (e.getValueIsAdjusting()) {
          return;
        } //Ignore extra messages.
        mainLSM_ = (ListSelectionModel) e.getSource();
        if (!mainLSM_.isSelectionEmpty()) {
          int selectedRow = mainLSM_.getMinSelectionIndex();
          rowSelected(selectedRow);
        }
      }
    });
    tScrollPane_ = new JScrollPane(table_);

    int left = (int) JPanel.LEFT_ALIGNMENT;

    nameText_ = GUIFactory.newTextField("", 64, 0);//new JTextField(15);
    nameText_.setEditable(false);
    nameText_.setAlignmentX(left);

    altNamesText_ = GUIFactory.newTextField("", 256, 0);
    altNamesText_.setEditable(false);
    nameText_.setAlignmentX(left);

    locText_ = GUIFactory.newTextField("", 64, 0);
    locText_.setEditable(false);
    locText_.setAlignmentX(left);

    editNameBtn_ = GUIFactory.newButton("Edit", 55, this);
    JPanel nameRow = new JPanel();
    nameRow.setLayout(new BoxLayout(nameRow, BoxLayout.X_AXIS));
    nameRow.add(nameText_);
    nameRow.add(editNameBtn_);
    nameRow.setAlignmentX(left);

    editAltNamesBtn_ = GUIFactory.newButton("Edit", 55, this);
    JPanel altNamesRow = new JPanel();
    altNamesRow.setLayout(new BoxLayout(altNamesRow, BoxLayout.X_AXIS));
    altNamesRow.add(altNamesText_);
    altNamesRow.add(editAltNamesBtn_);
    altNamesRow.setAlignmentX(left);

    editLocBtn_ = GUIFactory.newButton("Edit", 55, this);
    JPanel locRow = new JPanel();
    locRow.setLayout(new BoxLayout(locRow, BoxLayout.X_AXIS));
    locRow.add(locText_);
    locRow.add(editLocBtn_);
    locRow.setAlignmentX(left);


    JPanel propPanel = new JPanel();
    propPanel.setLayout(new BoxLayout(propPanel, BoxLayout.Y_AXIS));
    propPanel.setBorder(new CompoundBorder(new EmptyBorder(0, 3, 3, 3), new CompoundBorder(new TitledBorder("Landmark Properties"), new EmptyBorder(0, 3, 3, 3))));
    propPanel.add(new JLabel("Primary Name:", left));
    propPanel.add(nameRow);
    propPanel.add(Box.createVerticalStrut(5));
    propPanel.add(new JLabel("Alt. Names:", left));
    propPanel.add(altNamesRow);
    propPanel.add(Box.createVerticalStrut(5));
    propPanel.add(new JLabel("Location:", left));
    propPanel.add(locRow);

    locText_.setEnabled(true);

    // main button row:
    delBtn_ = GUIFactory.newButton("Delete", 50, this);
    newBtn_ = GUIFactory.newButton("New", 50, this);
    ;
    zoomBtn_ = GUIFactory.newButton("Zoom", 50, this);

    JPanel mainBtnRow = new JPanel();
    mainBtnRow.setLayout(new BoxLayout(mainBtnRow, BoxLayout.X_AXIS));
    mainBtnRow.add(Box.createHorizontalGlue());
    mainBtnRow.add(delBtn_);
    mainBtnRow.add(newBtn_);
    mainBtnRow.add(zoomBtn_);
    mainBtnRow.add(Box.createHorizontalGlue());


    JPanel rightPanel = new JPanel(new BorderLayout());
    rightPanel.add(propPanel, BorderLayout.CENTER);
    rightPanel.add(mainBtnRow, BorderLayout.SOUTH);


    JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, tScrollPane_, rightPanel);

    this.getContentPane().add(splitPane);

    pack();
    setSize(new Dimension(540, 320));
    splitPane.setDividerLocation(280);

    loadFromDB();
    noneSelected();

  } //*************** END OF CONSTRUCTOR ****************//

  public void show() {
    this.setLocation((av_.getGUI().getWidth() / 2) - getWidth() / 2 + av_.getGUI().getX(),
            (av_.getGUI().getHeight() / 2) - getHeight() / 2 + av_.getGUI().getY());
    super.show(); //setVisible(true);
    updateTable(true);
  }

  public void loadFromDB() {
    lmiList_ = av_.getEngine().getLandmarksNew().getLandmarks();
  }

  public void actionPerformed(ActionEvent e) {

    // edit actions:
    if (e.getSource() == editNameBtn_) {
      String curName = lmiList_.get(selRow_).name_;
      String newName = JOptionPane.showInputDialog("Landmark name:", curName);
      if (newName != null && newName.length() > 0 && !curName.equals(newName)) {
        av_.getEngine().getLandmarksNew().renameLandmark(curName, newName);
        loadFromDB();
        updateTable(false);
        noneSelected();
      }
    }

    if (e.getSource() == editAltNamesBtn_) {
      String selName = lmiList_.get(selRow_).name_;
      String altNames = JOptionPane.showInputDialog("Alternate names:", lmiList_.get(selRow_).altNames_);
      if (altNames != null && altNames.length() > 0) {
        av_.getEngine().getLandmarksNew().updateAltNames(selName, altNames);
        loadFromDB();
        updateTable(true);
      }
    }

    if (e.getSource() == editLocBtn_) {
      new LandmarkEditLocationDialog(av_, lmiList_.get(selRow_).name_, lmiList_.get(selRow_).altNames_);
    }

    if (e.getSource() == newBtn_) {
      av_.fireEvent(new ACEvent(EventTypes.LOC_NEW_LANDMARK));
    }

    if (e.getSource() == delBtn_) {
      if (selRow_ == -1) {
        av_.msg("No Landmark Selected");
        return;
      }
    // TODO: write new code
    //av_.getEngine().deleteLandmark(table_.getModel().getValueAt(selRow_,0).toString().toLowerCase());
    //selRow_ = -1;
    //updateTable(false); // calls noneSelected()
    }
    if (e.getSource() == zoomBtn_) {
      if (selRow_ == -1) {
        av_.msg("No Landmark Selected");
        return;
      }
      av_.specifyLocation(lmiList_.get(selRow_).locStr_);
    }
  }

  private void promptSelectNode() {
    toBack();
    JOptionPane.showMessageDialog(av_.getGUI(), "Select node from map.");
    av_.getGUI().setSpecialClickAction(ACGUI.SPECIAL_SELNODE_LM);
  }

  private void promptSelectTarget() {
    JOptionPane.showMessageDialog(this, "Select target");
  }

  private void setSelected(int i) {
    table_.setRowSelectionInterval(i, i);
    tScrollPane_.getVerticalScrollBar().setValue(i * (tScrollPane_.getVerticalScrollBar().getMaximum() / av_.getEngine().getLandmarksNew().landmarkCount()));
  }

  private TableModel getTableModel() {
    int lmCount = lmiList_.size();
    if (lmCount == 0) {
      return new DefaultTableModel();
    }
    String[] colNames = new String[3];
    colNames[0] = "Name";
    colNames[1] = "Location";
    colNames[2] = "Alt. Names";

    String[][] table = new String[lmCount][3];
    Iterator<Landmarks.LandmarkInfo> landmarks = lmiList_.iterator();
    for (int r = 0; r < lmCount; r++) {
      Landmarks.LandmarkInfo lmi = landmarks.next();
      table[r][0] = lmi.name_;
      table[r][1] = getLocationText(lmi);
      table[r][2] = lmi.altNames_;
    }
    return new DefaultTableModel(table, colNames);
  }

  private String getLocationText(Landmarks.LandmarkInfo lmi) {
    return (lmi.locStr_.startsWith("%") && lmi.locStr_.endsWith("%")) ? "Node " + lmi.locStr_.substring(1, lmi.locStr_.length() - 1) : lmi.locStr_;
  }

  public void updateTable(boolean preserveSelection) {
    table_.setModel(getTableModel());
    av_.msg("selRow: " + selRow_);
    if (preserveSelection && selRow_ != -1) {
      setSelected(selRow_);
    }
    if (!preserveSelection) {
      noneSelected();
    }
  }

  public void rowSelected(int index) {
    av_.msg("row selected: " + index);

    selRow_ = index;

    editNameBtn_.setEnabled(true);
    editAltNamesBtn_.setEnabled(true);
    editLocBtn_.setEnabled(true);

    Landmarks.LandmarkInfo lmi = lmiList_.get(index);
    nameText_.setText(lmi.name_);
    altNamesText_.setText(lmi.altNames_);
    locText_.setText(this.getLocationText(lmi));
  }

  public void noneSelected() {
    selRow_ = -1;
    editNameBtn_.setEnabled(false);
    editAltNamesBtn_.setEnabled(false);
    editLocBtn_.setEnabled(false);

    nameText_.setText("");
    altNamesText_.setText("");
    locText_.setText("");
  }
}

























